<!--
  * 分医馆 value 弹窗
  *
  * @Author:    小钟同学
  * @Date:      2022-06-08 21:50:41
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  小钟同学 （ https://1024lab.net ），Since 2012
-->
<template>
    <a-drawer :width="1000" :visible="visible" :body-style="{ paddingBottom: '80px' }" :title="DoctorRecordNameTitle"
              @close="onClose">
        <a-form class="smart-query-form">
            <a-row class="smart-query-form-row">

                <a-form-item label="驻点医馆" class="smart-query-form-item">
                    <a-select style="width: 200px" v-model:value="queryForm.si_number" optionFilterProp="title"
                              placeholder="请选择医生驻点医馆">
                        <a-select-option v-for="item in doctorStationNameList" :key="item.valueCode"
                                         :value="item.valueCode" :title="item.valueName">{{ item.valueName }}
                        </a-select-option>
                    </a-select>

                </a-form-item>

                <a-form-item label="时段" class="smart-query-form-item">

                    <a-select style="width: 200px" v-model:value="queryForm.ampm" placeholder="请选择上午还是下午">
                        <a-select-option value="am">上午</a-select-option>
                        <a-select-option value="pm">下午</a-select-option>
                    </a-select>

                </a-form-item>


                <a-form-item label="周几" class="smart-query-form-item">
                    <a-select style="width: 200px" v-model:value="queryForm.weekday" optionFilterProp="title"
                              placeholder="请选择出诊周期">
                        <a-select-option value="周一">周一</a-select-option>
                        <a-select-option value="周二">周二</a-select-option>
                        <a-select-option value="周三">周三</a-select-option>
                        <a-select-option value="周四">周四</a-select-option>
                        <a-select-option value="周五">周五</a-select-option>
                        <a-select-option value="周六">周六</a-select-option>
                        <a-select-option value="周日">周日</a-select-option>
                    </a-select>
                </a-form-item>


                <a-form-item label="排班日期" class="smart-query-form-item">
                    <a-space direction="vertical" :size="12">
                        <!--                        <a-range-picker v-model:value="searchDate" @change="dateChange"/>-->
                        <a-range-picker

                            v-model:value="queryForm.createTime" :ranges="defaultTimeRanges"
                                        style="width: 230px" @change="onChangeCreateTime"/>
                    </a-space>
                </a-form-item>






                <a-form-item class="smart-query-form-item smart-margin-left10">
                    <a-button type="primary" @click="ajaxQuery">
                        <template #icon>
                            <ReloadOutlined/>
                        </template>
                        查询
                    </a-button>
                    <a-button @click="resetQuery">
                        <template #icon>
                            <SearchOutlined/>
                        </template>
                        重置
                    </a-button>
                </a-form-item>
            </a-row>
        </a-form>

        <a-card size="small" :bordered="false">


            <a-row class="smart-table-btn-block">
                <div class="smart-table-operate-block">
                    <a-button @click="confirmBatchDelete" type="danger"
                              size="small" :disabled="selectedRowKeyList.length == 0">
                        <template #icon>
                            <DeleteOutlined/>
                        </template>
                        批量删除
                    </a-button>
                    <a-button type="primary" @click="showDoctorInterimSchedulingFormModal" size="small">
                        <template #icon>
                            <cloud-upload-outlined/>
                        </template>
                        新增临时排班
                    </a-button>
                </div>

                <div class="smart-table-setting-block">
                    <TableOperator class="smart-margin-bottom5" v-model="columns" :refresh="ajaxQuery"/>
                </div>
            </a-row>

            <a-table
                    :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
                    size="small"
                    :defaultExpandAllRows="true"
                    :dataSource="tableData"
                    :loading="tableLoading"
                    :columns="columns"
                    rowKey="id"
                    :pagination="false"
                    bordered
            >
                <template #bodyCell="{ record, column }">
                    <template v-if="column.dataIndex === 'action'">
                        <a-button @click="confirmSingleDelete(record)"
                                  type="link">删除
                        </a-button>

                    </template>

                    <template v-if="column.dataIndex === 'is_opened'">
                        <a-tag :color="record.is_opened==0 ? 'error' : 'orange'">
                            {{ record.is_opened == 0 ? '禁用' : '启用' }}
                        </a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'scheduling_status'">
                        <a-tag :color="record.status==0 ? 'error' : 'processing'">{{
                            record.scheduling_status == 1 ? '正常' : '失效'
                            }}
                        </a-tag>
                    </template>
                </template>
            </a-table>

            <div class="smart-query-table-page">
                <a-pagination
                        showSizeChanger
                        showQuickJumper
                        show-less-items
                        :pageSizeOptions="PAGE_SIZE_OPTIONS"
                        :defaultPageSize="queryForm.pageSize"
                        v-model:current="queryForm.pageNum"
                        v-model:pageSize="queryForm.pageSize"
                        :total="total"
                        @change="ajaxQuery"
                        @showSizeChange="ajaxQuery"
                        :show-total="(total) => `共${total}条`"
                />
            </div>
        </a-card>
        <DoctorInterimSchedulingFormModal ref="doctorInterimSchedulingFormModal" @reloadList="ajaxQuery"/>

    </a-drawer>
</template>
<script setup lang="ts">

// import DictValueOperateModal from '../dict-value-operate-modal.vue';
import {PAGE_SIZE_OPTIONS} from '/@/constants/common-const';
import {businessesApi} from '/@/api/system/infirmary/businesses-api';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {Modal} from 'ant-design-vue';
import {message} from 'ant-design-vue';
import {smartSentry} from '/@/lib/smart-sentry';
import DoctorInterimSchedulingFormModal from '../doctor-interim-scheduling-form-modal/index.vue';
import DoctorSchedulingRuleFormModal from '../doctor-scheduling-rule-form-modal/index.vue';
import {computed, createVNode, nextTick, onMounted, reactive, ref} from 'vue';
import TableOperator from "/@/components/support/table-operator/index.vue";
import {defaultTimeRanges} from "/@/lib/default-time-ranges";
import _ from "lodash";
// 是否展示抽屉
const visible = ref(false);
// 渠道ID
const Appid = ref(undefined);

// 医生实体记录
const DoctorRecord = ref(undefined);

const DoctorRecordNameTitle = ref(undefined);
const DoctorRecordName = ref(undefined);
const doctorInterimSchedulingFormModal = ref();
// 日期选择
let searchDate = ref();


// ----------------------- 表单显示 ---------------------
const doctorStationNameList = ref([]); //当前医馆驻点医馆列表
async function queryAllDoctorStationNameList(appid) {
    // 只查询当前要查询的APPID的医馆信息
    let res = await businessesApi.queryDoctorStationNameListValueList({
        'appid': appid
    });
    doctorStationNameList.value = res.data;
}


function showDoctorInterimSchedulingFormModal( ) {
    // SmartLoading.show();
    doctorInterimSchedulingFormModal.value.showDrawer(DoctorRecord.value,Appid.value);
    // SmartLoading.hide();
}

function onChangeCreateTime(dates, dateStrings) {
    queryForm.stime = dateStrings[0];
    queryForm.etime = dateStrings[1];
}


function showModal(record, appid) {
    Appid.value = appid;
    DoctorRecord.value = record;
    DoctorRecordNameTitle.value = "【" + record.name + "】" + "医生---驻点医馆排班详情信息"
    visible.value = true;
    ajaxQuery();
    DoctorRecordName.value = record.name
    nextTick(() => {
        // 执行异步获取医馆列表信息
        // 获取当前医馆的驻点的分医馆的列表
        queryAllDoctorStationNameList(appid);
    });
}

function onClose() {
    visible.value = false;
    Appid.value = undefined;
    DoctorRecord.value = undefined;
    searchDate.value = [];
    //重置也需要默认提交的值信息。需要保持不变
    queryFormState.appid = undefined;
    queryFormState.dc_number = undefined;
    Object.assign(queryForm, queryFormState);
}

const columns = reactive([
    {
        title: 'id',
        width: 50,
        dataIndex: 'id',
    },
    {
        title: '所属医馆',
        dataIndex: 'si_name',
        width: 150,
    },
    {
        title: '周几',
        dataIndex: 'weekday',
    },
    {
        title: '排班日期',
        dataIndex: 'scheduling_dnotime',
        width: 150,
    },
    {
        title: '上午下午',
        dataIndex: 'scheduling_ampm',
    },
    {
        title: '排班时段',
        dataIndex: 'scheduling_tiemampmstr',
        ellipsis: true,
    },
    {
        title: '总库存数',
        dataIndex: 'scheduling_stock',
    },
    {
        title: '排班状态',
        dataIndex: 'scheduling_status',
    },
    {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: 100,
    },
]);

// ----------------------- 表格 查询 ------------------------

const queryFormState = {
    si_name: undefined,
    appid: undefined,
    searchDate: undefined,
    dc_number: undefined,
    ampm: undefined,
    si_number: undefined,
    weekday: undefined,
    createTime: [], //创建时间
    stime: undefined, //创建时间 开始
    etime: undefined, //创建时间 结束
    pageNum: 1,
    pageSize: 10,
};
const queryForm = reactive({...queryFormState});
const selectedRowKeyList = ref([]);
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref(0);

const infirmaryStationFormModal = ref();
const doctorSchedulingRuleFormModal = ref();


// 显示操作记录弹窗

function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
}




function resetQuery() {
    // 所属的应用ID
    // queryForm.appid = DoctorRecord.value.appid;
    // 所属医生编号
    // queryForm.dc_number = DoctorRecord.value.dc_number;
    // createTime
    searchDate.value = [];
    //重置也需要默认提交的值信息。需要保持不变
    queryFormState.appid = DoctorRecord.value.appid
    queryFormState.dc_number = DoctorRecord.value.dc_number
    Object.assign(queryForm, queryFormState);
    selectedRowKeyList.value = []
    ajaxQuery();
}

async function ajaxQuery() {
    try {
        tableLoading.value = true;

        // 所属的应用ID
        queryForm.appid = Appid;
        // 所属医生编号
        queryForm.dc_number = DoctorRecord.value.dc_number;

        // console.log("输AAAAAAAAAAAA出",Appid,queryForm.appid)
        // 查询对应的驻点医馆列表信息
        let responseModel = await businessesApi.getBusinessesDoctorSchedulingDeasListQuery(queryForm);
        const list = responseModel.data.list;
        total.value = responseModel.data.total;
        // 遍历列表中的对象
        for (var i = 0; i < list.length; i++) {
            var obj = list[i];
            // 添加新的age属性
            obj.dc_name = DoctorRecordName.value; // 这里可以根据需要设置合适的年龄值
        }
        tableData.value = list;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        tableLoading.value = false;
    }
}

// ----------------------- 批量 删除 ------------------------
function confirmBatchDelete() {
    Modal.confirm({
        title: '提示',
        content: '确定要删除【当前页面选中医生排班记录】吗，删除后不可恢复哦！',
        okText: '删除',
        okType: 'danger',
        onOk() {
            batchDelete();
        },
        cancelText: '取消',
        onCancel() {},
    });
}

const batchDelete = async () => {
    try {
        SmartLoading.show();
        // await dictApi.keyDelete(selectedRowKeyList.value);
        console.log(selectedRowKeyList.value)
        // 取消APPID
        await businessesApi.deleteBatchBusinessesDoctorSchedulingDeasListQuery(Appid.value,DoctorRecord.value.dc_number,selectedRowKeyList.value);

        message.success('删除成功');
        ajaxQuery();
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide();
    }
};



function confirmSingleDelete(record) {
    Modal.confirm({
        title: '温馨提示',
        content: '注意：确定要删除选中的排班信息【'+record.weekday+'-'+record.scheduling_dnotime+'-'+record.scheduling_ampm+'-'+record.scheduling_tiemampmstr+ '】记录信息吗?',
        okText: '删除',
        okType: 'danger',
        onOk() {
            // batchDelete();
            requestDoctorSchedulingDeasDelete(record.id,record.appid,record.dc_number)
        },
        cancelText: '取消',
        onCancel() {
        },
    });
}

async function requestDoctorSchedulingDeasDelete(id,appid,dc_number) {
    SmartLoading.show();
    try {
        await businessesApi.deleteBusinessesDoctorSchedulingDeasListQuery(id,{
            'appid':appid,
            'dc_number':dc_number
        });
        message.success('删除成功!');
        ajaxQuery();
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        SmartLoading.hide();
    }
}
function doctorSchedulingModal() {
    // 临时排班需求弹窗模型需求
    Modal.confirm({
        title: '温馨提示',
        content: '注意：确定要删除选中的所有排班记录信息吗?',
        okText: '删除',
        okType: 'danger',
        onOk() {
            // batchDelete();
        },
        cancelText: '取消',
        onCancel() {
        },
    });
}



// ----------------------- 弹窗表单操作 ------------------------

// const operateModal = ref();
// function addOrUpdateValue(rowData) {
//   operateModal.value.showModal(rowData, dictKeyId.value);
// }

defineExpose({
    showModal,
});
</script>
